package com.zh.service.impl;

import com.alibaba.fastjson.JSON;
import com.zh.pojo.Content;
import com.zh.service.ContentService;
import com.zh.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    // 解析数据，放入es中
    @Override
    public Boolean parseContent(String keyword) throws IOException {
        HtmlParseUtil htmlParseUtil = new HtmlParseUtil();
        // 爬虫JD的数据
        List<Content> contents = htmlParseUtil.parseJD(keyword);

        // 批量插入到自己的es中
        BulkRequest bulkRequest = new BulkRequest();
        for (Content con : contents) {
            bulkRequest.add(new IndexRequest("zhang_index")
            .source(JSON.toJSONString(con), XContentType.JSON));
        }
        // 客户端发送请求
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
        return !bulk.hasFailures();// 是否失败， 成功返回false, 失败返回true
    }

    @Override
    public List<Map<String, Object>> search(String keyword, int page, int rows) throws IOException {
        // 条件搜索
        SearchRequest searchResult = new SearchRequest("zhang_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 分页
        searchSourceBuilder.size(rows); // 分页
        searchSourceBuilder.from(page); // 分页

        // 精准匹配
        TermQueryBuilder queryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(queryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); //设置超时时间

        // 高亮搜索
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false); // 多个高亮显示！
        highlightBuilder.field("title"); // 高亮的字段
        highlightBuilder.preTags("<span style='color:red'>"); // 高亮的前缀
        highlightBuilder.postTags("</span>"); //高亮的后缀
        searchSourceBuilder.highlighter(highlightBuilder);

        // 执行搜索
        searchResult.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchResult, RequestOptions.DEFAULT);

        // 解析结果
        List<Map<String, Object>> maps = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
//          没有加高亮的时候这样解析
//            maps.add(hit.getSourceAsMap());

            // 加完高亮之后的解析
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap(); //原来的结果
            if(title != null){
                Text[] fragments = title.fragments();
                String new_title = "";
                for (Text text : fragments) {
                    new_title += text;
                }
                System.out.println("new_title:"+new_title);
                sourceAsMap.put("title",new_title);
            }
            maps.add(sourceAsMap);
        }
        return maps;
    }
}















